#include "widget.h"

#include "ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);

  // excel = new QAxObject("Excel.Application");            /* connect */
  excel = new QAxObject(this); /* connect */

  if (false == excel->setControl("Excel.Application")) {
    if (false == excel->setControl("ket.Application")) {
      QMessageBox::information(NULL, "警告", "未安装office或者wps!\n");
      qApp->quit();
    }
  }

  excel->dynamicCall("SetVisible(bool Visible)", false); /* 可视化 */
  excel->setProperty("DisplayAlerts", false);            /* 警告 */
  workbooks = excel->querySubObject("WorkBooks"); /* 获取工作薄集合 */

  /*  进度条 */
  ui->progressBar->setMinimum(0);
  ui->progressBar->setValue(0);
  ui->progressBar->setFormat(
      QString("当前处理进度 : %1%").arg(QString::number(0.00, 'f', 1)));
  ui->progressBar->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
  QString versionInfo = QString("表格分解 by smaller");
  setWindowTitle(versionInfo);
  /* 设置icon */
  setWindowIcon(QIcon(":/img/ico_64.ico"));
}

Widget::~Widget() {
  delete excel;
  delete ui;
}

QString Widget::excelHCalc(int n) {
  QString h;
  while (n > 0) {
    h.prepend(static_cast<char>((n % 26) + 'A' - 1));
    n /= 26;
  }
  return h;
}

void Widget::writeExcel(QString fileName, QVariantList &list,
                        quint32 maxLineLength) {
  QAxObject *wExls = new QAxObject();
  QAxObject *wWorkBooks = new QAxObject();
  QAxObject *wWorkBook = new QAxObject();
  QAxObject *wWorkSheets = new QAxObject();
  QAxObject *wWorkSheet = new QAxObject();
  QAxObject *wWorkRange;

  if (false == wExls->setControl("Excel.Application")) {
    if (false == wExls->setControl("ket.Application")) {
      QMessageBox::information(NULL, "警告", "未安装office或者wps!\n");
      return;
    }
  }

  wExls->setProperty("Visible", false);            // 设置为可见
  wWorkBooks = wExls->querySubObject("WorkBooks"); // 操作表
  wWorkBooks->dynamicCall("Add");                  // 新建

  if (wExls->setProperty("Caption", "Qt Excel")) {
  } else {
    QMessageBox::information(this, "错误", "错误的Caption");
    return;
  }

  wWorkBook = wExls->querySubObject("ActiveWorkBook");
  wWorkSheets = wWorkBook->querySubObject("Sheets");
  wWorkSheet = wWorkSheets->querySubObject("Item(int)", 1);
  wWorkSheet->setProperty("Name", fileName); // 设置工作表名称

  QString range =
      QStringLiteral("A1:%1%2").arg(excelHCalc(maxLineLength)).arg(list.size());
  wWorkRange = wWorkSheet->querySubObject("Range(const QString&)", range); //
  wWorkRange->setProperty("Value", QVariant(list));

  QString filePath = ui->selectEdit_2->text() + QString("/");
  fileName = QString("%2_%1.xlsx")
                 .arg(QDateTime::currentDateTime().toString("yyyyMMddHHmmss"))
                 .arg(fileName);
  QDir dir;
  if (!dir.exists(filePath)) { // 如果文件夹不存在
    dir.mkpath(filePath);      //   则创建文件夹
  }
  wWorkBook->dynamicCall("SaveAs(const QString&)",
                         QDir::toNativeSeparators(filePath + fileName)); // 保存

  wExls->dynamicCall("Quit(void)");

  delete wWorkSheet;
  delete wWorkSheets;

  delete wWorkBook;
  delete wWorkBooks;
  delete wExls;
  return;
}

bool Widget::insterData(QList<exlsData *> &list, QString name,
                        QVariantList &data) {
  bool bRet = false;
  int i = 0, j = 0;
  quint32 dLen = 0;
  do {
    if (name.isEmpty())
      break;

    for (i = 0; i < list.length(); i++) {
      if (0 == QString::compare(name, list.at(i)->company, Qt::CaseSensitive)) {
        bRet = true;
        break;
      }
    }

    dLen = data.size();

    if (bRet == true) {
      /* 插入pos i */
      list.at(i)->lines.append(QVariant(data));
    } else {
      list.append(new exlsData(name, dLen));
      for (j = 0; j < srcHeadRow; j++) {
        list.at(list.length() - 1)
            ->lines.append(QVariant(srcList->at(j).toList()));
        if (list.at(0)->maxLen < (quint32)srcList->at(j).toList().size()) {
          list.at(0)->maxLen = (quint32)srcList->at(j).toList().size();
        }
      }
      list.at(list.length() - 1)->lines.append(QVariant(data));
    }

    if (list.at(0)->maxLen < dLen) {
      list.at(0)->maxLen = dLen;
    }
    bRet = true;
  } while (0);
  return bRet;
}

cRow_t Widget::getHeadInfo(QVariantList &data) {
  bool bRet = false;
  int iRet = 0;
  int cnt = 0;
  int column = 0;
  cRow_t vRet = {-1, -1};
  QVariantList rowData;
  do {
    cnt = 0;
    switch (data.size()) {
    case 0:
      break;
    default:
      rowData = data[cnt].toList();
      for (column = 0; column < rowData.size(); column++) {
        if (ui->usrEdit->text() == rowData.at(column).toString()) {
          goto findExit;
        }
      }
      cnt++;
    case 3:
      rowData = data[cnt].toList();
      for (column = 0; column < rowData.size(); column++) {
        if (ui->usrEdit->text() == rowData.at(column).toString()) {
          goto findExit;
        }
      }
      cnt++;
    case 2:
      rowData = data[cnt].toList();
      for (column = 0; column < rowData.size(); column++) {
        if (ui->usrEdit->text() == rowData.at(column).toString()) {
          goto findExit;
        }
      }
      cnt++;
    case 1:
      rowData = data[cnt].toList();
      for (column = 0; column < rowData.size(); column++) {
        if (ui->usrEdit->text() == rowData.at(column).toString()) {
          goto findExit;
        }
      }
      break;
    }
    if (bRet == false) {
      iRet = -1;
      break;
    }
  findExit : {
    vRet.column = column;
    vRet.row = cnt + 1;
    break;
  }
  } while (0);

  return vRet;
}

void Widget::on_selectBtn_clicked() {
  QString file = QFileDialog::getOpenFileName(
      this, tr("打开表格(excel)文件"),
      QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
      tr("表格文件 (*.xls *.xlsx)"));
  if (file.isEmpty()) {
    QMessageBox::information(this, "打开错误", "未选择表格文件\n");
    return;
  }
  ui->selectEdit->setText(file);
  exlsFile = file;
}

void Widget::on_procBtn_clicked() {
  /* 检测输入参数  */
  ui->progressBar->setValue(0);
  ui->progressBar->setFormat(
      QString("当前处理进度 : %1%").arg(QString::number(0, 'f', 1)));
  if (ui->usrEdit->text().isEmpty()) {
    QMessageBox::information(this, "警告", "请在列表项中输入筛选内容!\n");
    return;
  }
  if (ui->selectEdit->text().isEmpty()) {
    QMessageBox::information(this, "警告", "请选择表格文件!\n");
    return;
  }
  if (ui->selectEdit_2->text().isEmpty()) {
    QMessageBox::information(this, "警告", "请选择输出路径!\n");
    return;
  }
  /*
   * 1. 打开表格
   * 2. 获取表格数据
   * 3. 获取第一行数据,索引表头,找到对应的列
   * 4. 将找到的列数据进行比对写入列表
   * 5. 根据列表在进行行读取
   * 6. 将读取到的列依次写入文件
   *
   */
  workbooks->dynamicCall("Open(const QString&)",
                         QDir::toNativeSeparators(exlsFile)); /* open */
  workbook = excel->querySubObject("ActiveWorkBook");
  worksheets = workbook->querySubObject("Sheets");
  worksheet = worksheets->querySubObject("Item(int)", 1);

  QVariant var;
  QAxObject *usedRange = worksheet->querySubObject("UsedRange");
  var = usedRange->dynamicCall("Value");
  delete usedRange;
  QVariantList varRows = var.toList();
  if (varRows.isEmpty()) {
    return;
  }
  srcHeadRow = 0;
  cRow_t lineNum = getHeadInfo(varRows);
  if (0 > lineNum.row) {
    workbook->dynamicCall("Close()");
    return;
  }
  srcList = NULL;
  srcList = &varRows;
  srcHeadRow = lineNum.row;
  int rowT = 0;
  QVariantList varRowData;
  for (rowT = lineNum.row; rowT < varRows.size(); rowT++) {
    varRowData.clear();
    varRowData = varRows.at(rowT).toList();

    /* 归属地信息 */
    /* 查找归属地,未找到则new一个 添加,否则直接添加 */
    insterData(exlsLis, varRowData.at(lineNum.column).toString(), varRowData);
  }
  double dProgress = 0;
  ui->progressBar->setMaximum(exlsLis.length());
  for (rowT = 0; rowT < exlsLis.length(); rowT++) {
    ui->progressBar->setValue(rowT);

    dProgress = (ui->progressBar->value() - ui->progressBar->minimum()) *
                100.0 /
                (ui->progressBar->maximum() - ui->progressBar->minimum());

    ui->progressBar->setFormat(
        QString("当前处理进度 : %1%").arg(QString::number(dProgress, 'f', 1)));

    writeExcel(exlsLis.at(rowT)->company, exlsLis.at(rowT)->lines,
               exlsLis.at(0)->maxLen);
  }

  ui->progressBar->setFormat(
      QString("当前处理进度 : %1%").arg(QString::number(100.0, 'f', 1)));
  workbook->dynamicCall("Close()");

  QMessageBox::information(this, "提示", "处理完成");
  srcList = NULL;
  srcHeadRow = 0;
}

void Widget::on_selectBtn_2_clicked() {
  QString dir = QFileDialog::getExistingDirectory(
      this, tr("选择路径"),
      QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
      QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
  if (dir.isEmpty()) {
    QMessageBox::information(this, "打开错误", "未选择输出路径\n");
    return;
  }
  ui->selectEdit_2->setText(dir);
  // exlsFile = file;

}
